import {fetch} from 'fetch'
import qs from 'qs'
import stirageUtil from './AsyncStorageUtil'

function timeout_fetch(fetch_promise, timeout = 30000) {
    let timeout_fn = null;

    //这是一个可以被reject的promise
    let timeout_promise = new Promise(function (resolve, reject) {
        timeout_fn = function () {
            reject('timeout promise');
        };
    });

    //这里使用Promise.race，以最快 resolve 或 reject 的结果来传入后续绑定的回调
    let abortable_promise = Promise.race([
        fetch_promise,
        timeout_promise
    ]);

    setTimeout(function () {
        timeout_fn();
    }, timeout);

    return abortable_promise;
}
export const common_url = 'http://192.168.3.93:8080/';//钟
// export const common_url = 'http://192.168.3.4:8080/';  //王
// export const common_url = 'http://192.168.3.45:8080/';//司
// export const common_url = 'http://www.foreknow.net/';
/**
 * @param {string} url 接口地址
 * @param {string} method 请求方法：GET、POST，只能大写
 * @param {JSON} [params=''] body的请求参数，默认为空
 * @return 返回Promise
 */
export const header = {
    'Content-Type': 'application/x-www-form-urlencoded',
};
export const header2 = {
    "Content-Type": "application/json;charset=UTF-8"
}
export const header3 = {
    "Content-Type": "multipart/form-data"
}

stirageUtil.get("accountToken").then((token) => {//获取登录token
    header.accessToken = token
    header2.accessToken = token
    header3.accessToken = token
})

//测试
export function testFetch(url, method, params) {
    if (params === '') {
        return fetch(common_url + url, {
            method: method,
            headers: header
        })
    } else {
        return fetch(common_url + url, {
            method: method,
            headers: {
                "Content-Type": "application/json;charset=UTF-8",
                //'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: JSON.stringify(params)
        })
    }
}

//文件上传
export function upLoading(url, param) {
    let name = new Date().getTime() + ".jpg";
    let file = { uri: param.path, type: param.mime, name: name }
    let formData = new FormData();
    formData.append("file", file)

    return new Promise(function (resolve, reject) {
        timeout_fetch(fetch(common_url + url, {
            method: 'POST',
            headers: header3,
            body: formData
        })).then(response => response.json())
            .then((responseData) => {
                //console.log('res:', url, responseData);   //网络请求成功返回的数据
                resolve(responseData);
            }).catch((err) => {
                //console.log('err:', url, err);   //网络请求失败返回的数据
                reject(err);
            });
    });
}

//复杂对象提交
export function JsonFetch(url, method, params) {
    return new Promise(function (resolve, reject) {
        timeout_fetch(fetch(common_url + url, {
            method: method,
            headers: header2,
            body: JSON.stringify(params)   //body参数，通常需要转换成字符串后服务器才能解析
        })).then(response => response.json())
            .then((responseData) => {
                //console.log('res:', url, responseData);   //网络请求成功返回的数据
                resolve(responseData);
            }).catch((err) => {
                //console.log('err:', url, err);   //网络请求失败返回的数据
                reject(err);
            });
    });
}

//简单提交
export function fetchRequest(url, method, params = '') {
    if (params == '') {   //如果网络请求中没有参数
        return new Promise(function (resolve, reject) {
            timeout_fetch(fetch(common_url + url, {
                method: method,
                headers: header
            }))
                .then((response) => response.json())
                .then((responseData) => {
                    //console.log('res:', url, responseData);  //网络请求成功返回的数据
                    resolve(responseData);
                })
                .catch((err) => {
                    //console.log('err:', url, err);     //网络请求失败返回的数据
                    reject(err);
                });
        });
    } else {   //如果网络请求中带有参数
        return new Promise(function (resolve, reject) {
            timeout_fetch(fetch(common_url + url, {
                method: method,
                headers: header,
                body: qs.stringify(params)   //body参数，通常需要转换成字符串后服务器才能解析
            })).then(response => response.json())
                .then((responseData) => {
                    //console.log('res:', url, responseData);   //网络请求成功返回的数据
                    resolve(responseData);
                }).catch((err) => {
                    //console.log('err:', url, err);   //网络请求失败返回的数据
                    reject(err);
                });
        });
    }


}
